import * as React from 'react';
import { connect } from 'react-redux';
import { Dropdown, Modal, Menu, Card, message, Steps, Icon } from 'antd';

import './Index.scss';
import { fetchLevels, removeLevel } from 'actions/level';

import LoadableComponent from 'components/common/LoadableComponent';
const LoadableTestEdit = LoadableComponent(() => import('pages/lesson/test'));
const LoadableLevelEdit = LoadableComponent(() => import('./Edit'));
const Step = Steps.Step;

interface IndexProps {
  dispatch: (action: any) => any;
  lessonId: number;
}

interface IndexState {
  current: number;
  editLevel: any;
  levelList: any[];
}

class Index extends React.Component<IndexProps, IndexState> {
  static defaultProps: IndexProps = {
    dispatch: () => {},
    lessonId: 0,
  };
  constructor(props: IndexProps) {
    super(props);
    this.state = {
      current: -1,
      levelList: [],
      editLevel: null,
    };
  }

  componentDidMount() {
    this.handleFetchLevels();
  }

  componentWillReceiveProps(nextProps: any) {
    const { lessonId } = nextProps;
    const { lessonId: oldLessonId } = this.props;

    if (lessonId !== oldLessonId) {
      if (lessonId) {
        this.handleFetchLevels(lessonId);
      } else {
        this.setState({
          current: -1,
          levelList: [],
        });
      }
    }
  }

  handleFetchLevels = (lessonId: number = this.props.lessonId) => {
    const { dispatch } = this.props;
    dispatch(fetchLevels(lessonId)).then((result: any) => {
      if (result.code) {
        message.error(result.msg);
      } else {
        this.setState({
          levelList: result.response.data.items,
        });
      }
    });
  };

  handleChangeStep = (current: number) => {
    this.setState({
      current,
    });
  };

  openLevelModal = (editLevel: any = 0) => {
    const { levelList } = this.state;
    this.setState({
      editLevel,
      current: editLevel ? editLevel.level - 1 : levelList.length > 0 ? levelList.length : 0,
    });
  };
  closeLevelModal = () => {
    this.setState({
      editLevel: null,
    });
  };

  handleTrashConfirm = (item: any) => {
    Modal.confirm({
      title: '危险',
      content: '你确定要删除此关卡及关卡所有测试数据吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        this.handleTrash(item);
      },
    });
  };

  handleTrash = (level: any) => {
    const { dispatch, lessonId } = this.props;
    dispatch(removeLevel(lessonId, level.id)).then((result: any) => {
      if (result.code) {
        message.error(result.msg);
      } else {
        message.success('关卡删除成功');
        this.handleChangeStep(-1);
        this.handleFetchLevels();
      }
    });
  };

  renderAction(item: any) {
    const menu = (
      <Menu>
        <Menu.Item>
          <a
            onClick={e => {
              e.preventDefault();
              this.openLevelModal(item);
            }}
            href="javascript: void 0;">
            <Icon type="edit" />
            编辑关卡
          </a>
        </Menu.Item>
        <Menu.Item>
          <a
            onClick={e => {
              e.preventDefault();
              this.handleTrashConfirm(item);
            }}
            href="javascript: void 0;">
            <Icon type="delete" />
            删除
          </a>
        </Menu.Item>
      </Menu>
    );

    return (
      <Dropdown key={item.id} overlay={menu} trigger={['click']}>
        <a className="ant-dropdown-link">
          <Icon type="down" />
        </a>
      </Dropdown>
    );
  }

  render() {
    const { lessonId } = this.props;
    const { current, editLevel, levelList } = this.state;

    return (
      <div>
        <Card className="level-list-card">
          <Steps current={current} size="small">
            {levelList.map((item: any, index: number) => {
              const title = [this.renderAction(item)];
              return (
                <Step
                  key={item.id}
                  title={title}
                  description={item.description}
                  status={current === index ? 'process' : 'wait'}
                  onClick={() => {
                    this.handleChangeStep(index);
                  }}
                />
              );
            })}
            <Step
              title="新增关卡"
              onClick={() => {
                this.openLevelModal();
              }}
            />
          </Steps>
        </Card>
        {current >= 0 &&
          levelList.length > current && (
            <Card className="level-test-card">
              <LoadableTestEdit lessonId={lessonId} levelId={levelList[current]['id']} />
            </Card>
          )}

        {editLevel !== null && (
          <LoadableLevelEdit
            level={current + 1}
            lessonId={lessonId}
            editLevel={editLevel}
            onOk={() => {
              this.handleFetchLevels();
            }}
            onCancel={() => {
              this.closeLevelModal();
            }}
          />
        )}
      </div>
    );
  }
}

interface OwnProps {
  lessonId: number;
}
function mapStateToProps(state: any, ownProps: OwnProps) {
  const { lessonId } = ownProps;

  return {
    lessonId,
  };
}

export default connect(mapStateToProps)(Index);
